/**
 * 爬虫配置管理相关逻辑
 * @type {*}
 */
var pageObj = $('#page');
var pageSize = 50;
var cPage = 1;
var dataList;

//初始化
function init() {
    // page, pageSize
    loadData(cPage);
}

function processPage(data) {
    // 处理分页
    pageObj.children().remove();
    pageObj.append('<div id="create_page_num"></div>');
    pageObj.find("#create_page_num").createPage({
        pageCount: data.pages,
        current: data.pageNum,
        backFn: function (p) {
            loadData(p, pageSize);
        }
    });
}

/**
 * 查询列表
 */
function searchList() {
    loadData(cPage);
}

// 加载分页列表
function loadData(pageNo) {
    $.ajax({
        url: "/manage/crawler/list",
        type: 'POST',
        data: {
               pageNum: pageNo,
               pageSize: pageSize,
               name:$('#name').val(),
               remark:$('#remark').val(),
               createTimeStart:$('#createTimeStart').val(),
               createTimeEnd:$('#createTimeEnd').val()
        },
        success: function (data) {
            console.log(data);
            dataList = data.data.list;
            var allDataHtml = "";
            for (var i = 0; i < dataList.length; i++) {
                var cData = dataList[i];
                var cHtml =
                    "<tr data-id=\"" + cData.id + "\" data-no=\"" + cData.no + "\">\n" +
                    "<td>" + cData.id + "</td>\n" +
                    "<td>" + cData.name + "</td>\n" +
                    "<td>" + cData.edenUrl + "</td>\n" +
                    "<td>" + cData.remark + "</td>\n" +
                    "<td>" + cData.createTime + "</td>\n" +
                    "<td>" + cData.updateTime + "</td>\n" +
                    "<td>" + cData.status + "</td>\n" +
                    "<td>\n" +
                    "<a href=\"javascript:saveCrawler('" + i + "');\">修改</a>\n";
                    if(cData.status == 'RUNABLE'){
                        cHtml += "<a href=\"javascript:stopCrawler('" + cData.id + "');\" class=\"red-link\">停用</a>\n";
                    } else {
                        cHtml += "<a href=\"javascript:startCrawler('" + cData.id + "');\" class=\"red-link\">启用</a>\n";
                    }
                    cHtml += "</td>\n" +
                    "</tr>";
                allDataHtml += cHtml;
            }
            $("#resultList").html();
            $("#resultList").html(allDataHtml);

            // 处理分页
            cPage = pageNo;
            processPage(data.data);
        }
    });
}

//创建爬虫
function saveCrawler(index) {
    var title ='爬虫修改';
    var crawlerInfo = null;
    if (null == index || "" == index) {
        title ='爬虫新建';
        crawlerInfo = {
            id:"",
            name:"",
            edenUrl:"",
            nextRegex:"",
            destUrlXpath:"",
            destContentXpath:"",
            remark:""
        }
    }else{
        crawlerInfo = dataList[index];
    }

    var arr = '<div class="createTarget">' +
        '<ul>' +
        '<input type="hidden" id="cid" name="cid" value="'+crawlerInfo.id +'" />' +
        '<li>' +
        '<span>名称：</span>' +
        '<input type="text" id="cname" name="cname" value="'+crawlerInfo.name +'" />' +
        '</li>' +
        '<li>' +
        '<span>入口地址：</span>' +
        '<textarea rows="3" cols="20" name="cedenUrl" id="cedenUrl">'+crawlerInfo.edenUrl+'</textarea>' +
        '</li>' +
        '<li>' +
        '<span>下一步规则：</span>' +
        '<textarea rows="3" cols="20" name="cnextRegex" id="cnextRegex">'+crawlerInfo.nextRegex+'</textarea>' +
        '</li>' +
        '<li>' +
        '<span>目标地址Xpath规则：</span>' +
        '<textarea rows="3" cols="20" name="cdestUrlXpath" id="cdestUrlXpath">'+crawlerInfo.destUrlXpath+'</textarea>' +
        '</li>' +
        '<li>' +
        '<span>目标内容Xpath规则：</span>' +
        '<textarea rows="3" cols="20" name="cdestContentXpath" id="cdestContentXpath">'+crawlerInfo.destContentXpath+'</textarea>' +
        '</li>' +
        '<li>' +
        '<span>网站来源：</span>' +
        '<input type="text" name="cremark" id="cremark" value="'+crawlerInfo.remark +'" />' +
        '</li>' +
        '</ul>' +
        '</div>';

    var config = {
        title: title,
        body: arr,
        btn: [
            {
                title: '确定',
                className: 'button btn-ok btn-radius',
                dimiss: false,
                callback: function(){
                    return checkQualified();
                }
            },
            {
                title: '取消',
                className: 'button btn-blue-line btn-radius',
                dimiss: false,
                callback: function(){
                    return true;
                }
            }
        ]
    };
    createModalDom(config);
    $('#myModal').modal('show');
}

//检查输入的内容
function checkQualified() {
    var _id = $("#cid"),
        _name = $("#cname"),        //名称
        _edenUrl = $("#cedenUrl"),   //入口地址
        _nextRegex = $("#cnextRegex"),   //下一步规则
        _destUrlXpath = $("#cdestUrlXpath"),   //目标地址xpath规则
        _destContentXpath = $("#cdestContentXpath"),   //目标内容xpath规则
        _remark = $("#cremark"); //网站来源

    $.ajax({
        url: "/manage/crawler/save",
        type: "post",
        data: {
            id: _id.val(),
            name: _name.val(),
            edenUrl: _edenUrl.val(),
            nextRegex: _nextRegex.val(),
            destUrlXpath: _destUrlXpath.val(),
            destContentXpath: _destContentXpath.val(),
            remark: _remark.val()
        },
        success: function(data){
            if (data.status) {
                if(_id.val() == "" || _id.val() == null) {
                    alert("爬虫新建成功");
                } else {
                    alert("爬虫修改成功");
                }
                loadData(cPage);
            } else {
                if(_id.val() == "" || _id.val() == null) {
                    alert("爬虫新建失败");
                } else {
                    alert("爬虫修改失败");
                }
            }
        },
        fail: function(data) {
            console.error("服务器内部错误");
        }
    });
    return true;
}

// 停用爬虫
function stopCrawler(id) {
    if(!confirm("确认停用当前爬虫?")) {
        return false;
    }
    $.ajax({
        url: "/manage/crawler/stop",
        type: "POST",
        data: {id: id},
        success: function(data) {
            if (data.status) {
                alert("停用成功");
                loadData(cPage);
            } else {
                alert("停用失败");
            }
        },
        fail: function(){
            console.error("网络异常或服务器内部错误，请联系管理员");
        }
    })
}

// 启动爬虫
function startCrawler(id) {
    if(!confirm("确认启用当前爬虫?")) {
        return false;
    }
    $.ajax({
        url: "/manage/crawler/start",
        type: "POST",
        data: {id: id},
        success: function(data) {
            if (data.status) {
                alert("启动成功");
                loadData(cPage);
            } else {
                alert("启动失败");
            }
        },
        fail: function(){
            console.error("网络异常或服务器内部错误，请联系管理员");
        }
    })
}


